/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import javax.inject.Inject;

import ru.irenproject.pad.Pad;
import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Event;
import ru.irenproject.store.Stash;
import ru.irenproject.store.Thing;

public final class PadBrief extends AbstractThing implements Brief {
  private static final int SOFT_LIMIT = 50;
  private static final int HARD_LIMIT = SOFT_LIMIT + 15;

  public static PadBrief create(Pad pad) {
    PadBrief res = pad.store().create(PadBrief.class);
    res.prepare(pad);
    return res;
  }

  @Stash private UiProtos.PadBrief.Builder $;

  @Inject PadBrief() {}

  private void prepare(Pad pad) {
    $.setPad(pad.id());
    pad.addListener(this);
  }

  private Pad pad() {
    return get($.getPad(), Pad.class);
  }

  @Override public String text() {
    return pad().getBrief(SOFT_LIMIT, HARD_LIMIT);
  }

  @Override protected void handleEvent(Event e, Thing source) {
    if (e instanceof Pad.ChangeEvent) {
      post(ChangeEvent.INSTANCE);
    }
  }
}
